package com.example.homemate.service.impl.house;

import com.example.homemate.model.entity.house.House;
import com.example.homemate.Repository.house.HouseRepository;
import com.example.homemate.service.house.HouseService;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class HouseServiceImpl implements HouseService {

    private static final Logger logger = LoggerFactory.getLogger(HouseServiceImpl.class);

    @Autowired
    private HouseRepository houseRepository;

    @Override
    @Transactional
    public Page<House> searchHouses(
            Pageable pageable,
            String houseNumber,
            String status,
            Long ownerId
    ) {
        // 构建查询条件
        Specification<House> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 房号模糊查询
            if (houseNumber != null && !houseNumber.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(
                        root.get("houseNumber"), "%" + houseNumber.trim() + "%"
                ));
            }

            // 状态精确查询
            if (status != null && !status.trim().isEmpty()) {
                try {
                    House.Status statusEnum = House.Status.valueOf(status.toUpperCase());
                    predicates.add(criteriaBuilder.equal(root.get("status"), statusEnum));
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的房屋状态: " + status);
                }
            }

            // 业主ID关联查询
            if (ownerId != null) {
                Join<House, Object> ownerJoin = root.join("ownerId", JoinType.LEFT);
                predicates.add(criteriaBuilder.equal(ownerJoin, ownerId));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        // 执行带条件的分页查询
        return houseRepository.findAll(spec, pageable);
    }

    @Override
    @Transactional
    public House saveHouse(House house) {
        return houseRepository.save(house);
    }

    @Override
    @Transactional
    public void deleteHouse(Long id) {
        houseRepository.deleteById(id);
    }

    @Override
    @Transactional
    public House updateHouse(Long id, House updatedHouse) {
        House existingHouse = houseRepository.findById(id)
                .orElseThrow(() -> new HouseNotFoundException("房屋不存在，ID: " + id));

        existingHouse.setHouseNumber(updatedHouse.getHouseNumber());
        existingHouse.setArea(updatedHouse.getArea());
        existingHouse.setLayout(updatedHouse.getLayout());
        existingHouse.setFloor(updatedHouse.getFloor());
        existingHouse.setUnit(updatedHouse.getUnit());
        existingHouse.setStatus(updatedHouse.getStatus());
        existingHouse.setOwner(updatedHouse.getOwner());
        existingHouse.setDetails(updatedHouse.getDetails());

        return houseRepository.save(existingHouse);
    }

    @Override
    @Transactional
    public House getHouseById(Long id) {
        return houseRepository.findById(id)
                .orElseThrow(() -> new HouseNotFoundException("无效房屋ID: " + id));
    }

    @Override
    @Transactional
    public List<House> getAllHouses() {
        return houseRepository.findAll();
    }

    // 自定义异常类
    class HouseNotFoundException extends RuntimeException {
        public HouseNotFoundException(String message) {
            super(message);
        }
    }
}